package com.gmall.security.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.gmall.common.model.Response;
import com.gmall.security.vo.JwtUser;
import com.gmall.user.api.po.User;
import com.gmall.user.api.provider.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 获取用户信息 (内部校验密码)
        User user = userClient.findUserByName(s);
        if(user == null){
            throw new UsernameNotFoundException("抱歉，未查询到相关用户名");
        }
        // 查询用户角色权限
        Response<JSONObject> response = userClient.getAccountInfo((String) user.getId());
        Map map = JSONObject.parseObject(JSON.toJSONString(response.getData()),Map.class);
        if(map.get("role") != null){
            List<String> roles = JSON.parseObject(JSON.toJSONString(map.get("role")),new TypeReference<List<String>>(){});
            user.setRoles(roles);
        }
        return new JwtUser(user);
    }
}
